<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1>学习中心数据大屏</h1>
      <div class="time-range-selector">
        <el-select v-model="selectedTimeRange" placeholder="选择时间范围" @change="fetchDashboardData">
          <el-option label="最近7天" value="7d"></el-option>
          <el-option label="最近30天" value="30d"></el-option>
          <el-option label="最近90天" value="90d"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <i class="el-icon-video-play card-icon"></i>
              <div class="card-info">
                <div class="card-number">{{ dashboardData.totalCourses || 0 }}</div>
                <div class="card-label">总课程数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <i class="el-icon-document card-icon"></i>
              <div class="card-info">
                <div class="card-number">{{ dashboardData.totalQuestions || 0 }}</div>
                <div class="card-label">总问题数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <i class="el-icon-user card-icon"></i>
              <div class="card-info">
                <div class="card-number">{{ dashboardData.totalStudents || 0 }}</div>
                <div class="card-label">学生总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <i class="el-icon-star card-icon"></i>
              <div class="card-info">
                <div class="card-number">{{ dashboardData.totalPoints || 0 }}</div>
                <div class="card-label">学习积分</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <!-- 课程分布图表 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>课程分布</span>
              </div>
            </template>
            <div class="chart-wrapper">
              <div ref="courseDistributionChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 问题状态统计图表 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>问题状态统计</span>
              </div>
            </template>
            <div class="chart-wrapper">
              <div ref="questionStatusChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 学习进度趋势 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>学习进度趋势</span>
              </div>
            </template>
            <div class="chart-wrapper">
              <div ref="learningTrendChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 学生学习活跃度 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>学生学习活跃度</span>
              </div>
            </template>
            <div class="chart-wrapper">
              <div ref="studentActivityChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 热门课程排行 -->
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>热门课程排行</span>
              </div>
            </template>
            <div class="chart-wrapper">
              <div ref="popularCoursesChart" class="chart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getDashboardData } from '@/utils/dashboardApi'

// 时间范围选择
const selectedTimeRange = ref('7d')

// 图表引用
const courseDistributionChart = ref<HTMLDivElement>()
const questionStatusChart = ref<HTMLDivElement>()
const learningTrendChart = ref<HTMLDivElement>()
const studentActivityChart = ref<HTMLDivElement>()
const popularCoursesChart = ref<HTMLDivElement>()

// 仪表板数据
const dashboardData = ref({
  totalCourses: 0,
  totalQuestions: 0,
  totalStudents: 0,
  totalPoints: 0,
  courseDistribution: [],
  questionStatus: [],
  learningTrend: [],
  studentActivity: [],
  popularCourses: []
})

// 图表实例
let courseDistributionInstance: echarts.ECharts | null = null
let questionStatusInstance: echarts.ECharts | null = null
let learningTrendInstance: echarts.ECharts | null = null
let studentActivityInstance: echarts.ECharts | null = null
let popularCoursesInstance: echarts.ECharts | null = null

// 获取仪表板数据
async function fetchDashboardData() {
  try {
    console.log('正在获取仪表板数据...')
    const response = await getDashboardData(selectedTimeRange.value)
    console.log('API响应:', response)
    
    // 确保正确处理响应数据结构
    let dataToUse = response
    if (response && response.data) {
      // 如果是包装过的响应
      dataToUse = response.data
    }
    
    if (dataToUse && typeof dataToUse === 'object') {
      // 使用完整的数据结构，添加默认值确保不会为null
      dashboardData.value = {
        totalCourses: dataToUse.totalCourses !== undefined ? dataToUse.totalCourses : 0,
        totalQuestions: dataToUse.totalQuestions !== undefined ? dataToUse.totalQuestions : 0,
        totalStudents: dataToUse.totalStudents !== undefined ? dataToUse.totalStudents : 0,
        totalPoints: dataToUse.totalPoints !== undefined ? dataToUse.totalPoints : 0,
        courseDistribution: Array.isArray(dataToUse.courseDistribution) ? dataToUse.courseDistribution : [],
        questionStatus: Array.isArray(dataToUse.questionStatus) ? dataToUse.questionStatus : [],
        learningTrend: Array.isArray(dataToUse.learningTrend) ? dataToUse.learningTrend : [],
        studentActivity: Array.isArray(dataToUse.studentActivity) ? dataToUse.studentActivity : [],
        popularCourses: Array.isArray(dataToUse.popularCourses) ? dataToUse.popularCourses : []
      }
      console.log('处理后的dashboardData:', dashboardData.value)
      renderCharts()
    } else {
      console.error('无效的响应数据:', response)
      ElMessage.error('获取数据失败')
    }
  } catch (error) {
    console.error('获取仪表板数据失败:', error)
    ElMessage.error('网络错误，获取数据失败')
  }
}

// 渲染所有图表
function renderCharts() {
  console.log('开始渲染图表，数据:', dashboardData.value)
  
  // 渲染课程分布图
  if (courseDistributionChart.value) {
    if (courseDistributionInstance) {
      courseDistributionInstance.dispose()
    }
    courseDistributionInstance = echarts.init(courseDistributionChart.value)
    
    const option = {
      title: {
        text: '课程分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '课程分类',
          type: 'pie',
          radius: '50%',
          data: dashboardData.value.courseDistribution && Array.isArray(dashboardData.value.courseDistribution) ? 
            dashboardData.value.courseDistribution : [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    courseDistributionInstance.setOption(option)
  }

  // 渲染问题状态统计图
  if (questionStatusChart.value) {
    if (questionStatusInstance) {
      questionStatusInstance.dispose()
    }
    questionStatusInstance = echarts.init(questionStatusChart.value)
    
    const option = {
      title: {
        text: '问题状态统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: ['开放', '已解决', '已关闭']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '问题数量',
          type: 'bar',
          data: dashboardData.value.questionStatus && Array.isArray(dashboardData.value.questionStatus) ? 
            dashboardData.value.questionStatus : [0, 0, 0],
          itemStyle: {
            color: '#409EFF'
          }
        }
      ]
    }
    questionStatusInstance.setOption(option)
  }

  // 渲染学习进度趋势图
  if (learningTrendChart.value) {
    if (learningTrendInstance) {
      learningTrendInstance.dispose()
    }
    learningTrendInstance = echarts.init(learningTrendChart.value)
    
    const option = {
      title: {
        text: '学习进度趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      },
      yAxis: {
        type: 'value',
        name: '完成率 (%)'
      },
      series: [
        {
          name: '学习完成率',
          type: 'line',
          data: dashboardData.value.learningTrend && Array.isArray(dashboardData.value.learningTrend) ? 
            dashboardData.value.learningTrend : [0, 0, 0, 0, 0, 0, 0],
          smooth: true,
          itemStyle: {
            color: '#67C23A'
          }
        }
      ]
    }
    learningTrendInstance.setOption(option)
  }

  // 渲染学生学习活跃度图
  if (studentActivityChart.value) {
    if (studentActivityInstance) {
      studentActivityInstance.dispose()
    }
    studentActivityInstance = echarts.init(studentActivityChart.value)
    
    const option = {
      title: {
        text: '学生学习活跃度',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: ['0-10分', '11-30分', '31-50分', '51-70分', '71-90分', '91-100分']
      },
      yAxis: {
        type: 'value',
        name: '学生人数'
      },
      series: [
        {
          name: '学生数量',
          type: 'bar',
          data: (dashboardData.value.studentActivity && 
                 Array.isArray(dashboardData.value.studentActivity) && 
                 dashboardData.value.studentActivity.map(item => item.count)) || [0, 0, 0, 0, 0, 0],
          itemStyle: {
            color: '#E6A23C'
          }
        }
      ]
    }
    studentActivityInstance.setOption(option)
  }

  // 渲染热门课程排行图
  if (popularCoursesChart.value) {
    if (popularCoursesInstance) {
      popularCoursesInstance.dispose()
    }
    popularCoursesInstance = echarts.init(popularCoursesChart.value)
    
    const option = {
      title: {
        text: '热门课程排行',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'value',
        boundaryGap: [0, 0.01]
      },
      yAxis: {
        type: 'category',
        data: (dashboardData.value.popularCourses && 
               Array.isArray(dashboardData.value.popularCourses) && 
               dashboardData.value.popularCourses.map(item => item.courseName)) || []
      },
      series: [
        {
          name: '学习人数',
          type: 'bar',
          data: (dashboardData.value.popularCourses && 
                 Array.isArray(dashboardData.value.popularCourses) && 
                 dashboardData.value.popularCourses.map(item => item.studentCount)) || [],
          itemStyle: {
            color: '#F56C6C'
          }
        }
      ]
    }
    popularCoursesInstance.setOption(option)
  }
}

// 图表自适应
function handleResize() {
  if (courseDistributionInstance) courseDistributionInstance.resize()
  if (questionStatusInstance) questionStatusInstance.resize()
  if (learningTrendInstance) learningTrendInstance.resize()
  if (studentActivityInstance) studentActivityInstance.resize()
  if (popularCoursesInstance) popularCoursesInstance.resize()
}

// 监听窗口大小变化
onMounted(() => {
  fetchDashboardData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  if (courseDistributionInstance) courseDistributionInstance.dispose()
  if (questionStatusInstance) questionStatusInstance.dispose()
  if (learningTrendInstance) learningTrendInstance.dispose()
  if (studentActivityInstance) studentActivityInstance.dispose()
  if (popularCoursesInstance) popularCoursesInstance.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
}

.dashboard-header h1 {
  color: #303133;
  margin: 0;
}

.time-range-selector {
  width: 200px;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.card-icon {
  font-size: 32px;
  margin-right: 15px;
  color: #409eff;
}

.card-info {
  display: flex;
  flex-direction: column;
}

.card-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.card-label {
  font-size: 14px;
  color: #606266;
  margin-top: 5px;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.chart-wrapper {
  height: 300px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>